<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" :close-on-press-escape="false" width="900" :close-on-click-modal="false" center>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="attraction-form">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="名称" prop="name">
              <el-input v-model="formData.name" placeholder="如：三中回迁房" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
                <el-option label="住宅" value="住宅" />
                <el-option label="公寓" value="公寓" />
                <el-option label="写字楼" value="写字楼" />
                <el-option label="厂房" value="厂房" />
                <el-option label="仓库" value="仓库" />
                <el-option label="商铺" value="商铺" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售价" prop="price">
              <div style="display: flex">
                <el-input v-model="formData.price" style="width: 100%" placeholder="填写售价" :disabled="formData.facePrice" />
                <el-button @click="() => (formData.facePrice = !formData.facePrice)">面议</el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input-number v-model="formData.area" :min="0" :max="999" :precision="0" style="width: 100%" placeholder="面积 (平方米)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="布局" prop="layout">
              <el-input v-model="formData.layout" style="width: 100%" placeholder="如：3室2厅1卫" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="楼层" prop="floorInfo">
              <el-input v-model="formData.floorInfo" style="width: 100%" placeholder="如：12/28层" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修建年份" prop="buildYear">
              <el-input-number v-model="formData.buildYear" :min="0" :max="9999" :precision="0" style="width: 100%" placeholder="修建年份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推荐" prop="isFeatured">
              <el-switch v-model="formData.isFeatured" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-row v-for="(item, index) in listPhone">
              <el-col :span="6">
                <el-form-item label="联系人" prop="phone" span="12">
                  <el-input v-model="item.name" placeholder="姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-input v-model="item.phone" placeholder="联系电话">
                  <template #append>
                    <el-button @click="handleFormatPhone(item)">格式化</el-button>
                  </template>
                </el-input>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="10">
            <el-form-item label="坐标位置" prop="position">
              <el-input v-model="formData.position" placeholder="坐标位置" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" clearable>
                <template #append>
                  <el-button :icon="Location" @click="handleShowPosition" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 标签管理 -->
      <div class="form-section">
        <h3 class="section-title">标签管理</h3>
        <el-form-item label="房间设施" prop="tagsJson">
          <div class="tags-container">
            <el-tag v-for="tag in formData.tagsJson" :key="tag" closable @close="removeTag(tag)" class="tag-item">
              {{ tag }}
            </el-tag>
            <el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" class="tag-input" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
            <el-button v-else class="button-new-tag" size="small" @click="showInput"> + 添加标签 </el-button>
          </div>
        </el-form-item>
        <el-form-item label="常用标签：">
          <div class="preset-tags">
            <el-tag v-for="tag in presetTags" :key="tag" class="preset-tag" @click="addPresetTag(tag)" :class="{ disabled: formData.tagsJson.includes(tag) }">
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
      </div>

      <!-- 描述信息 -->
      <div class="form-section">
        <h3 class="section-title">描述信息</h3>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入详细描述，包括特色等" maxlength="500" show-word-limit />
        </el-form-item>
      </div>

      <!-- 图片管理 -->
      <div class="form-section">
        <h3 class="section-title">图片管理</h3>
        <el-form-item label="图片">
          <div class="image-upload-container">
            <el-upload v-model:file-list="imageFileList" :headers="fileHeader" :action="formAction" :on-success="handleImageUpload" list-type="picture-card" :auto-upload="true" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" multiple>
              <el-icon><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="">
          <div class="upload-tip">
            <el-text size="small" type="info"> 支持 jpg、png、gif 格式，单张图片不超过 2MB，最多上传 5 张 </el-text>
          </div>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布售房' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <LocationView ref="refLocationView" @change="handlePositionChange" />
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Location } from '@element-plus/icons-vue'
import http from '@/apis/house'
import type { FormInstance, FormRules, UploadFile, UploadUserFile, UploadProps } from 'element-plus'
import LocationView from '@/components/location.vue'

import { useUserStore } from '@/stores/user'
const refLocationView = ref<typeof LocationView>()

const handleShowPosition = () => {
  // console.log(formData.value.position)
  refLocationView.value?.handleShow(formData.value.position)
}

interface positionType {
  location: string
  lat: number
  lng: number
}

const handlePositionChange = (obj: positionType) => {
  // console.log(obj)
  formData.value.position = obj.location
}

const dialogTitle = ref('新增数据')
const userStore = useUserStore()
const submitting = ref(false)
const user = computed(() => userStore.userInfo)

const listPhone = ref<Array<any>>([
  { name: '', phone: '' },
  { name: '', phone: '' }
])

const host = import.meta.env.VITE_BASE_URL

const formAction = ref(host + '/api/sysFile/uploadFile')
const fileHeader = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token')
})

// 响应式数据
const formRef = ref<FormInstance>()
const inputRef = ref()
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const inputVisible = ref(false)
const inputValue = ref('')

const fileList = ref<UploadUserFile[]>([])

// 表单数据
const formData = ref({
  name: '', // 房产名称
  type: '', // 房产类型
  layout: '', // 户型（如：2室1厅1卫）
  address: '', // 详细地址
  area: 30, // 面积（平方米）
  buildYear: 2000, // 建筑年份
  city: '昆明市', // 城市
  phone: '', // 联系电话
  contactPerson: '', // 联系人
  description: '', // 房产描述
  district: '东川区', // 区域
  floorInfo: '', // 楼层
  imageUrls: [], // 图片地址
  phoneNumbers: '[]',
  isEnabled: true, // 是否启用
  isFeatured: false, // 是否推荐
  position: '', // 坐标位置
  price: 100000, // 价格（元）
  facePrice: false, //
  province: '云南省', // 省份
  tagsJson: ['近地铁', '拎包入住'] // 标签
})

// 预设标签
const presetTags = ref(['黄金地段', '临街商铺', '高人流', '拎包入住', '精装修', '南北通透', '豪华装修'])

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [{ required: true, message: '请选择分类', trigger: 'change' }],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入面积', trigger: 'blur' },
    { type: 'number', min: 0, message: '面积不能小于0', trigger: 'blur' }
  ]
}

const removeTag = (tag: string) => {
  const index = formData.value.tagsJson.indexOf(tag)
  if (index > -1) {
    formData.value.tagsJson.splice(index, 1)
  }
}

const handleFormatPhone = (obj: any) => {
  obj.phone = obj.phone.replace(/ /g, '').replace(/-/g, '')
}
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !formData.value.tagsJson.includes(inputValue.value)) {
    formData.value.tagsJson.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const addPresetTag = (tag: string) => {
  if (!formData.value.tagsJson.includes(tag)) {
    formData.value.tagsJson.push(tag)
  }
}

const imageUrls = new Array()
const imageFileList = ref<UploadFile[]>([])

const handleImageUpload = (response: any) => {
  // console.log('Logo上传结果:', response)
  let { code, message, result } = response
  if (code === 200) {
    let url = `${host}/${result.url}`
    imageUrls.push(url)
    ElMessage.success('上传成功')
    // console.log('上传成功', url)
  } else {
    ElMessage.error('上传失败: ' + response.message)
  }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  const index = imageFileList.value.findIndex((item) => item.uid === uploadFile.uid)
  if (index > -1) {
    imageUrls.splice(index, 1)
    imageFileList.value.splice(index, 1)
  }
  // console.log(uploadFile, uploadFiles)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value,
      tagsJson: '',
      imageUrls: ''
    }
    submitData.tagsJson = JSON.stringify(formData.value.tagsJson)
    submitData.imageUrls = JSON.stringify(imageUrls)

    submitData.phoneNumbers = JSON.stringify(listPhone.value)
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}

const emit = defineEmits(['update', 'create'])
const editMode = ref(false)
const handleCreate = (obj: any) => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false
  imageFileList.value = []
  imageUrls.splice(0x00, imageUrls.length)
  formData.value = {
    name: '', // 房产名称
    phoneNumbers: '[]',
    type: '住宅', // 房产类型
    layout: '', // 户型（如：2室1厅1卫）
    phone: '', // 联系电话
    contactPerson: '', // 联系人
    address: '', // 详细地址
    area: 70, // 面积（平方米）
    buildYear: 2000, // 建筑年份
    city: '昆明市', // 城市
    description: '', // 房产描述
    district: '东川区', // 区域
    floorInfo: '', // 楼层
    imageUrls: [], // 图片地址
    isEnabled: true, // 是否启用
    isFeatured: false, // 是否推荐
    position: '', // 坐标位置
    price: 100000, // 价格（元）
    facePrice: false, //
    province: '云南省', // 省份
    tagsJson: ['拎包入住'] // 标签
  }

  listPhone.value = [
    { name: '', phone: '' },
    { name: '', phone: '' }
  ]

  if (!obj) {
    return
  }
  formData.value = { ...obj }
  listPhone.value = JSON.parse(obj.phoneNumbers)
  formData.value.tagsJson = JSON.parse(obj.tagsJson)
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'
  formData.value.tagsJson = JSON.parse(obj.tagsJson)
  imageFileList.value = []
  imageUrls.splice(0x00, imageUrls.length)
  if (obj.phoneNumbers) {
    listPhone.value = JSON.parse(obj.phoneNumbers)
  }
  if (!obj.imageUrls) {
    return
  }
  let imgs = JSON.parse(obj.imageUrls)
  imageUrls.splice(0x00, 0, ...imgs)
  imgs.forEach((t: string, index: number) => {
    imageFileList.value.push({ url: t, uid: 100 + index, name: 'file_' + index, status: 'success' })
  })
  //   console.log(obj)
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  display: flex;
  flex-wrap: wrap;
}

.form-section {
  margin: 10px 10px;
  flex: 1 1;
  min-width: 400px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.preset-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.preset-tag {
  cursor: pointer;
}
</style>
